package com.jl.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jl.constants.UserRole;
import com.jl.mapper.AuthMapper;
import com.jl.model.Poker;
import com.jl.model.User;
import com.jl.model.vo.UserVo;
import com.jl.utils.AESUtil;
import com.jl.utils.UserInfoContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@Component
public class GetUserInfoService {

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private AuthMapper authMapper;

    private String key = "1234567890123456";


    public void setUserToRedis(User user){
        User user1 = authMapper.selectUserInfo(user.getOpenId());
        UserVo userVo = new UserVo();
        userVo.setHeadImgUrl(user.getHeadImgUrl());
        userVo.setOpenId(user.getOpenId());
        userVo.setNickName(user.getNickName());
        userVo.setPhone(user.getPhone());
        userVo.setCoin(user.getCoin());
        if (user1!=null){
            userVo.setId(user1.getId());
            userVo.setUserRole(user1.getUserRole());
        }
        redisTemplate.opsForValue().set(user.getId()+"_baseInfo", JSONObject.toJSONString(userVo));
    }

    public UserVo getUserByUserId(Integer userId){
        String s = null;
        Object o = redisTemplate.opsForValue().get(userId + "_baseInfo");
        if (o!=null){
            s = o.toString();
            return JSONObject.parseObject(s, UserVo.class);
        }
        return null;
    }

    /*
    保存接口调用TOKEN
     */
    public String setUserToken(String userId){
        String userTokenKey = userId+"_userToken";
        String userToken = null;
        try {
            userToken = AESUtil.Encrypt(userTokenKey + System.currentTimeMillis(),key);
            redisTemplate.opsForValue().set(userTokenKey,userToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userToken;
    }


    public UserVo getUserByToken(String token){
        try {
            String decrypt = AESUtil.Decrypt(token, key);
            if (!StringUtils.isEmpty(decrypt)){
                String userId = decrypt.split("_")[0];
                return getUserByUserId(Integer.valueOf(userId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean isManager(){
        UserVo user = UserInfoContext.getUser();
        if (user.getUserRole().equals(UserRole.管理员.getValue())){
            return true;
        }
        return false;
    }

    public void setUserRealTime(User user){
        redisTemplate.opsForValue().set(user.getId()+"_account",user.getCoin().toString());
    }

    public BigDecimal getUserRealTime(User user){
        String coin = null;
        Object o = redisTemplate.opsForValue().get(user.getId() + "_account");
        if (o!=null){
            coin = o.toString();
            return new BigDecimal(coin);
        }else {
            User user1 = authMapper.selectByPrimaryKey(user);
            return user1.getCoin();
        }
    }

    /*
    保存用户当前手牌
     */
    public void setUserPoker(List<Poker> poker,Integer userId){
        redisTemplate.opsForHash().put("poker",userId+"_poker",JSONObject.toJSONString(poker));
    }

    /*
    删除用户当前手牌
     */
    public void deleteUserPoker(Integer userId){
        redisTemplate.opsForHash().delete("poker",userId+"_poker");
    }

    /*
    获取用户当前手牌
     */
    public List<Poker> getUserPoker(Integer userId){
        Object poker = redisTemplate.opsForHash().get("poker", userId + "_poker");
        if (poker!=null){
            return JSONArray.parseArray(poker.toString(), Poker.class);
        }
        return null;
    }

    public static void main(String[] args) {
        GetUserInfoService getUserInfoService = new GetUserInfoService();
        String liuyong123 = getUserInfoService.encrypt("Jinluan123");
        System.out.println(liuyong123);
    }

    /*
    用户密码加密
     */
    public String encrypt(String password){
        try {
            String encrypt = AESUtil.Encrypt(password, key);
            return encrypt;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /*
    用户密码解密
     */
    public String decrypt(String password){
        try {
            String decrypt = AESUtil.Decrypt(password, key);
            return decrypt;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /*
    账户更变
    type 1=加 2减
     */
    public void changeAccount(Integer type,Integer userId,BigDecimal numb){
        UserVo userByUserId = getUserByUserId(userId);
        BigDecimal coin = userByUserId.getCoin();
        switch (type){
            case 1:
                coin = coin.add(numb);break;
            case 2:
                coin = coin.subtract(numb); break;
        }
        if (coin.compareTo(new BigDecimal(0))<=0){
            coin = new BigDecimal(0);
        }
        changeCoin(userId,coin);
    }

    public void changeCoin(Integer userId,BigDecimal coin){
        UserVo userByUserId = getUserByUserId(userId);
        userByUserId.setCoin(coin);
        redisTemplate.opsForValue().set(userId+"_baseInfo", JSONObject.toJSONString(userByUserId));
        User user = new User();
        user.setId(userId);
        user.setCoin(coin);
        setUserRealTime(user);
        authMapper.updateByPrimaryKeySelective(user);
    }


}
